/**
 * Copyright 2010 MiSSO4J author(s)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sjsso.cas.servlet;

import static org.sjsso.Constant.NONCES;
import static org.sjsso.Constant.SESSIONS;
import static org.sjsso.Constant.SESSION_USER;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.sjsso.model.User;

@SuppressWarnings("serial")
public class BaseServlet extends HttpServlet {

	protected void addToSessionMap(User user) {
		Map<String, User> sessions = getSessionMap();
		sessions.put(user.getToken(), user);
		setMap(SESSIONS, sessions);
	}

	protected void removeFromSessionMap(String id) {
		Map<String, User> sessions = getSessionMap();
		sessions.remove(id);
		setMap(SESSIONS, sessions);
	}
	
	protected void addToNonceList(String nonce, String token) {
		Map<String, String> nonces = getNonceMap();
		nonces.put(nonce, token);
		setMap(NONCES, nonces);
	}

	protected void removeFromNonceList(String nonce) {
		Map<String, String> nonces = getNonceMap();
		nonces.remove(nonce);
		setMap(NONCES, nonces);
	}

	protected void setMap(String name, Object value) {
		ServletContext context = this.getServletContext();
		context.setAttribute(name, value);
	}
	
	@SuppressWarnings("unchecked")
	protected Map<String, String> getNonceMap() {
		ServletContext context = this.getServletContext();
		return (Map<String, String>) context.getAttribute(NONCES);
	}
	
	@SuppressWarnings("unchecked")
	protected Map<String, User> getSessionMap() {
		ServletContext context = this.getServletContext();
		return (Map<String, User>) context.getAttribute(SESSIONS);
	}
	
	protected User getUser(HttpServletRequest request) {
		return (User) request.getSession().getAttribute(SESSION_USER);
	}

}